<?php

/**
 * sfGuardRegister actions.
 *
 * @package    guard
 * @subpackage sfGuardRegister
 * @author     Francisco Calderón <fjcalderon@gmail.com>
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z jwage $
 */
 
ProjectConfiguration::registerContacts();
ProjectConfiguration::registerTemplate();

class sfGuardRegisterActions extends sfActions
{
  public function executeIndex(sfWebRequest $request)
  {
    if ($this->getUser()->isAuthenticated())
    {
      $this->getUser()->setFlash('notice', 'You are already registered and signed in!');
      $this->redirect('@home');
    }

    $this->form = new sfGuardRegisterForm();
    $this->location = Doctrine_Core::getTable('GeoLocation')->getLocationByIp(getenv('REMOTE_ADDR'));
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $user = $form->save();
      return $user;
    }
  }
  
  public function executeSave(sfWebRequest $request)
  {
    if ($this->getUser()->isAuthenticated())
    {
      $this->getUser()->setFlash('notice', 'You are already registered and signed in!');
      $this->redirect('@home');
    }

    $form = new sfGuardRegisterForm();

    if ($request->isMethod('post'))
    {
      $user = $this->processForm($request, $form);

	    $mailer = $this->getMailer();
	    
      $message = Swift_Message::newInstance('Welcome to NearFriendzz');
      $message->setFrom(array('register@nearfriendzz.com' => sfConfig::get('app_default_email_name')));
      $message->setTo($user->email_address);
      
      // embeding files in to the message and obtain the image path
      $toplogo = $message->embed(Swift_Image::fromPath(sfConfig::get('sf_web_dir').'/images/email/toplogo.jpg'));
      $leftshadow = $message->embed(Swift_Image::fromPath(sfConfig::get('sf_web_dir').'/images/email/leftshadow.jpg'));
      $rightshadow = $message->embed(Swift_Image::fromPath(sfConfig::get('sf_web_dir').'/images/email/rightshadow.jpg'));
      $down = $message->embed(Swift_Image::fromPath(sfConfig::get('sf_web_dir').'/images/email/down.jpg'));

      $replacements[$user->email_address] = array(
        '{name}' => $user->first_name." ".$user->last_name,
        '{toplogo}' => $toplogo,
        '{leftshadow}' => $leftshadow,
        '{rightshadow}' => $rightshadow,
        '{down}' => $down
      );
			
	    $decorator = new Swift_Plugins_DecoratorPlugin($replacements);
      $mailer->registerPlugin($decorator);

      $message->setBody($this->getMessageBody('register'), 'text/html');

      //Send the message
      $mailer->send($message);

      return $this->renderText($user->id);
    }
  }

  protected function getMessageBody($template)
  {
    $loader = new sfTemplateLoaderFilesystem(sfConfig::get('sf_app_template_dir').'/emails/%name%.php');
    $engine = new sfTemplateEngine($loader);
    return $engine->render($template);
  }
  
  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    $params = $request->getParameter('sf_guard_user');
    $this->forward404Unless($user = Doctrine_Core::getTable('sfGuardUser')->find($params['id']));
    foreach($params['activities_list'] as $activity_id)
    {
      $activityUser = new sfGuardUserHasNfActivitiy();
      $activityUser->user_id = $user->id;
      $activityUser->nf_activitiy_id = $activity_id;
      $activityUser->save();
    }
    $user->location_id = $params['location_id'];
    $user->interests = $params['interests'];
    $user->save();
    return $this->renderText("success");
  }

  public function executeAjaxValidateFieldUser(sfWebRequest $request)
  {
    if($request->getParameter('fieldId') == 'sf_guard_user_username')
    {
      $user = Doctrine_Core::getTable('sfGuardUser')->findOneByUsername($request->getParameter('fieldValue'));
      if($user)
      {
        $response = array($request->getParameter('fieldId'), false, "");
      }else{
        $response = array($request->getParameter('fieldId'), true, "");
      }
    }elseif($request->getParameter('fieldId') == 'sf_guard_user_email_address')
    {
      $user = Doctrine_Core::getTable('sfGuardUser')->findOneByEmailAddress($request->getParameter('fieldValue'));
      if($user)
      {
        $response = array($request->getParameter('fieldId'), false, "");
      }else{
        $response = array($request->getParameter('fieldId'), true, "");
      }
    }
    return $this->renderText(htmlspecialchars(json_encode($response), ENT_NOQUOTES));
  }

  public function executeUploadFile(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));
    // list of valid extensions, ex. array("jpeg", "xml", "bmp")
    $allowedExtensions = array("jpeg", "jpg", "png", "gif");
    // max file size in bytes
    $sizeLimit = 2 * 1024 * 1024;
    $uploader = new FileUploader($allowedExtensions, $sizeLimit);
    $result = $uploader->handleUpload(sfConfig::get('sf_upload_dir').'/photos/');
    if($result['success']){
      $user = Doctrine_Core::getTable('sfGuardUser')->find(array($request->getParameter('user_id')));
      $user->photo = $uploader->filename;
      $thumbnail = new sfThumbnail(120, 120);
      $thumbnail->loadFile(sfConfig::get('sf_upload_dir').'/photos/'.$uploader->filename);
      $thumbnail->save(sfConfig::get('sf_upload_dir').'/photos/thumbs/'.$uploader->filename);
      $user->save();
    }
    // to pass data through iframe you will need to encode all html tags
    return $this->renderText(htmlspecialchars(json_encode($result), ENT_NOQUOTES));
  }
  
  public function executeGetLocation(sfWebRequest $request)
  {
    $location = Doctrine_Core::getTable('GeoLocation')->getLocationByCity($request->getParameter('q'));
    $resp = "";
    foreach($location as $loc)
    {
      $resp.= $loc->city. ", ".$loc->NfCountry->printable_name."|".$loc->loc_id."\n";
    }
    return $this->renderText($resp);
  }

  public function executeDone(sfWebRequest $request)
  {
  }
  
  public function executeActivities(sfWebRequest $request)
  {
    if ($this->getUser()->isAuthenticated())
    {
      $this->getUser()->setFlash('notice', 'You are already registered and signed in!');
      $this->redirect('@home');
    }
    if ($request->isMethod('post'))
    {
      $user = Doctrine_Core::getTable('sfGuardUser')->find($request->getParameter('sf_guard_user_id'));
      Doctrine_Core::getTable('sfGuardUserHasNfActivity')->delByUserId($request->getParameter('sf_guard_user_id'));
      foreach($request->getParameter('activities') as $activity_id)
      {
        $activityUser = new sfGuardUserHasNfActivity();
        $activityUser->user_id = $user->id;
        $activityUser->nf_activity_id = $activity_id;
        $activityUser->save();
      }
      $activities = Doctrine_Core::getTable('sfGuardUserHasNfActivity')->findByUserId($request->getParameter('sf_guard_user_id'));
      $li = '';
      foreach($activities as $activity)
      {
        $op.= "<option>".$activity->NfActivity."</option>";
      }
      return $this->renderText($op);
    }else
    {
      $this->activities = Doctrine_Core::getTable('NfActivity')->findAll();
      $this->user_id = $request->getParameter('user_id');
    }
  }
}
